package controllers

import (
	"strconv"

	"cashew.com/cashew_api/dtos"
	"cashew.com/cashew_api/models"
	"cashew.com/cashew_api/services"
	"cashew.com/cashew_api/tasks"
	"cashew.com/cashew_common/constants"
	"github.com/beego/beego/v2/core/logs"
)

type FreeChatController struct {
	BaseController
}

/*
* 自由聊天
 */
func (c *FreeChatController) SendMessage() {

	req := dtos.SendMessageParams{}
	err := dtos.Bind(&req, c.Ctx)

	if err != nil {
		c.Error("参数错误: ", err)
		c.Result(constants.ERR_PARAM, nil)
		return
	}

	userId := req.UserId
	toUserId, _ := strconv.ParseInt(req.ToUserId, 10, 64)

	// 获取用户身份
	identity := req.UserInfo.Identity
	toUserIdentity := req.ToUserInfo.Identity

	// 判断黑名单
	blackStatus := models.BlackStatus(userId, toUserId)
	if blackStatus == constants.BLACK_STATUS_FROM_OTHER {
		c.Result(constants.ERR_BLACK_STATUS_FROM_OTHER, nil)
		return
	} else if blackStatus == constants.BLACK_STATUS_FROM_ME {
		c.Result(constants.ERR_BLACK_STATUS_FROM_ME, nil)
		return
	}

	res := dtos.SendChatRes{
		ChatUnlock:   true,
		ChatPayPrice: 0,
		Identity:     identity,
		FreeCount:    0,
		SendStatus:   true,
	}

	// IM 通知
	// 查询接收消息的用户在线状态，判断发离线消息还是在线消息
	isOnline := true
	if toUserIdentity == constants.IDENTITY_NORMAL_USER || toUserIdentity == constants.IDENTITY_APPLY_ANCHOR {
		toUserInfo, err := models.GetUsersByUserId(toUserId)
		if err != nil {
			c.Error("GetUsersByUserId(%v): %v", toUserId, err)
			c.Result(constants.ERR_USER_NOT_EXIST, nil)
			return
		}
		if toUserInfo.Status == constants.ANCHOR_OFFLINE {
			isOnline = false
		}
	} else {
		toUserInfo, err := models.GetAnchor_infoByAnchorId(toUserId)
		if err != nil {
			c.Error("GetAnchor_infoByAnchorId(%v): %v", toUserId, err)
			c.Result(constants.ERR_USER_NOT_EXIST, nil)
			return
		}
		if toUserInfo.Status == constants.ANCHOR_OFFLINE {
			isOnline = false
		}
	}

	noticeUserId := req.ToUserId
	reqIm := services.AssembleImSendMessageRequest(&req, identity, noticeUserId, isOnline)
	err = services.ImSendMessage(&reqIm)
	if err != nil {
		c.Error("IM 通知失败：imChat(%+v): %v", req, err)
		c.Result(constants.ERR_IM_SENDM_FAIL, nil)
		return
	}

	// 如果用户离线，发应用外推送消息
	logs.Debug("用户%d(%s)发给用户%d(%s)的私聊消息，是否在线：%t", userId, toUserId, isOnline)
	if !isOnline {
		logs.Debug("发送离线消息")
		reqCoco, _ := services.AssembleCocoPushMessageReq2(identity, &req)
		_ = tasks.SubmitCocoPushTask(reqCoco)
	}
	c.Result(constants.SUCCESS, res)
	return
}
